﻿using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;

using G.Model;

namespace GameLibrary.Internal
{
    internal class SpaceSerializer
    {
        public static string toString(GameSpaceDef pGameDef)
        {
            DataContractSerializer serializer = 
                new DataContractSerializer(typeof(GameSpaceDef));
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            try
            {
                serializer.WriteObject(writer, pGameDef);
            }
            catch (Exception e)
            {
                pGameDef = new GameSpaceDef();
                stringWriter = new StringWriter();
                writer = new XmlTextWriter(stringWriter);
                serializer.WriteObject(writer, pGameDef);
                Console.WriteLine(e);
            }
            return stringWriter.ToString();
        }
        
        public static GameSpaceDef toObjectManifestResource(Assembly assembly, string name)
        {
            string found = null;
            string[] names = assembly.GetManifestResourceNames();
            foreach (string test in names) 
            {
                if (test.Contains(name))
                {
                    found = test;
                    break;
                }
            }
            if (found == null)
            {
                throw new ArgumentException(name + " not found");
            }
            
            StringWriter buf = new StringWriter();
            Stream stream = assembly.GetManifestResourceStream(found);
            TextReader reader = new StreamReader(stream);
            
            string line;
            while((line = reader.ReadLine()) != null)
            {
                buf.Write(line.Trim());
            }
            
            return toObject(buf.ToString());
        }
        
        public static GameSpaceDef toObject(string xml)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);
            DataContractSerializer serializer =
                new DataContractSerializer(typeof(GameSpaceDef));
            
            GameSpaceDef result = new GameSpaceDef();
            if (xml.Trim().Length > 0)
            {
                result = (GameSpaceDef)serializer.ReadObject(reader);
                result.PostInit();
            }
            
            return result;
        }
    }
}
